package com.loan.controller;

import com.loan.dto.Result;
import com.loan.entity.Notice;
import com.loan.repository.NoticeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * Created by huxudong on 17/7/10.
 */
@Controller
@RequestMapping("admin/notice")
public class NoticeController {

    @Autowired
    private NoticeRepository noticeRepository;


    /**
     * 列表
     * @return
     */
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public String list(Model model) {
        List<Notice> list = noticeRepository.findAll();
        model.addAttribute("list", list);
        return "notice/list";
    }

    /**
     * 新增or编辑
     * @return
     */
    @RequestMapping(value = "add",method = RequestMethod.GET)
    public String add(Model model,Long id) {
        if(id != null){
            Notice notice = noticeRepository.getOne(id);
            model.addAttribute("notice", notice);
        }

        return "notice/add";
    }

    /**
     * 保存
     * @return
     */
    @RequestMapping(value = "save",method = RequestMethod.POST)
    @ResponseBody
    public Result save(Notice notice) {
        Result result = new Result(200,"添加成功");
        if(notice.getId() == null){
            notice.setaTime(new Date());

        }else{
            Notice dbNotice = noticeRepository.getOne(notice.getId());
            notice.setaTime(dbNotice.getaTime());
        }

        notice.setcTime(new Date());
        noticeRepository.save(notice);
        return result;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public Result delete(Long id) {
        Result result = new Result(200,"添加成功");
        noticeRepository.delete(id);
        return result;
    }

}
